using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;

public partial class AlertPopup : System.Web.UI.Page
{
    // HtmlForm frmObj;
    string strErrMessage = "";
    HDDatabase HDD;
    DynamicDisplayI DDI;
    SqlCommand sqlcmd;
    ArrayList arrSqlCmd = new ArrayList();
    ScreenReader SR;
    string target_settings = "";
    HtmlForm frmObj;
    //string strErrMessage = "";
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        HDD = new HDDatabase();
        string refresh_time = "";
        int interval = 0;
        ClientScript.GetPostBackEventReference(this, string.Empty);

        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //hih_user_id.Value = Session["user_afrowid"].ToString();
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }


        try
        {
            target_settings = HDD.GetColumnValue("select mem_id  from sy_acr_mem where acr_id='7b9bf6c6ccfe8f43' and mem_name='remidertarget'");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :Get Target Setting in AlertPopup()" + ex.Message);
           
        }
        finally
        {
            HDD = null;
        }
       
        
        
        CheckforTask();
        GetDuedate();




        if (Page.IsPostBack == false)
        {
            LoadDDL();
        }
    }
    public void LoadDDL()
    {
        BindControl BC = new BindControl();
        HDDatabase Hdd = new HDDatabase();
        DataTable dt = new DataTable();
        dt = Hdd.GetDataTable("select mem_id, mem_name from sy_acr_mem where acr_id='a1f7486385b04df0' order by mem_seq");
        ddl_deferred.DataSource = dt;
        ddl_deferred.DataTextField = "mem_name";
        ddl_deferred.DataValueField = "mem_id";
        ddl_deferred.DataBind();
        ddl_deferred.Items.Insert(0, new ListItem("--Select--", ""));
        Hdd = null;
    }
    public void GetDuedate()
    {
        DataSet dsFunc;
        DataView dv;
        HDDatabase hd = new HDDatabase();
        GenerateAlerts GA = new GenerateAlerts();
        GridAlert = GA.LoadGrid(GridAlert);
        GA = null;

        
        GridAlert.Columns[0].ItemStyle.Width = 80;
        GridAlert.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        GridAlert.Columns[0].ItemStyle.VerticalAlign = VerticalAlign.Middle;
        if (GridAlert.Rows.Count != 0)
        {
            //lbl_task.Value = GridAlert.Rows[0].Cells[2].Text;
            // lbl_finish_date.Value = GridAlert.Rows[0].Cells[4].Text;
        }
        else
        {

            //  lbl_task.Visible = false;

            //header.Visible = false;
            bt_defer.Visible = false;
            bt_dismiss.Visible = false;
            bt_task_completed.Visible = false; // Added by 'Imran Gani' on 06-Mar-2014
            ddl_deferred.Visible = false;
        }
        DynamicDisplayI ddi = new DynamicDisplayI();
        Localization loc = new Localization();
        BindControl BC = new BindControl();
        HDD = new HDDatabase();
        try
        {
            

            for (int i = 0; i < GridAlert.Rows.Count; i++)
            {

                string duein = "";
                string strUTCoffset = "";
                strUTCoffset = ddi.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
                System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(HttpContext.Current.Session["userlocale"].ToString());
                GridAlert.Rows[i].Cells[5].Text = loc.getDateTime4TimeZone(GridAlert.Rows[i].Cells[5].Text, strUTCoffset, false, false);
                DateTime finish_dt = Convert.ToDateTime(loc.getDateTime4TimeZone(GridAlert.Rows[i].Cells[4].Text, strUTCoffset, false, false),ci);
                 //GridAlert.Rows[i].Cells[5].Text = GetUserTime(GridAlert.Rows[i].Cells[5].Text, strUTCoffset, false);
                 //DateTime finish_dt = Convert.ToDateTime(GetUserTime(GridAlert.Rows[i].Cells[4].Text, strUTCoffset, false), ci);
                DateTime Now = DateTime.Now;


                TimeSpan TS = finish_dt - Now;
                CheckBox chk_Select = new CheckBox();
                chk_Select.ID = "chk_Select_Reminders_View_" + i.ToString();
                chk_Select.Attributes.Add("onclick", "javascript:enableViewReminderButton();");
                GridAlert.Rows[i].Cells[0].Controls.Add(chk_Select);
                HyperLink link = new HyperLink();
                link.ID = "link_" + i.ToString();
                //link.Width = 210;
                link.Font.Name = "Arial";
                // link.Font.Size = 10;
                link.Target = "_" + target_settings;
                GridAlert.Rows[i].Cells[2].Wrap = true;
                GridAlert.Rows[i].Cells[2].Controls.Add(link);
                // GridAlert.Rows[i].Cells[0].Width = "50px";
                if (TS.Days == 0)
                    duein = TS.Hours.ToString() + " hours " + TS.Minutes.ToString() + " Minutes ";
                else
                    duein = TS.Days.ToString() + " days " + TS.Hours.ToString() + " hours ";

                string snow = Convert.ToString(DateTime.Now.ToUniversalTime());
                snow = loc.getDateTime4TimeZone(snow, strUTCoffset, false, true);
                //DateTime now = Convert.ToDateTime(snow);
                //DateTime now =  DateTime.Parse(snow, loc.getUserCulture()); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                DateTime now = DateTime.Parse(snow, MBLocale.MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString())); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
                if (finish_dt < now)
                    duein += " overdue";
                
                duein = duein.Replace("-", "");
                HtmlTableRow tr_Status = new HtmlTableRow();
                string sql = "";
                sql = BC.GetBindSql("39a618457d4e579b");

                DataTable dt_status = HDD.GetDataTable(sql);

                for (int j = 0; j < dt_status.Rows.Count; j++)
                {
                    if (GridAlert.Rows[i].Cells[3].Text == dt_status.Rows[j]["Val"].ToString())
                        GridAlert.Rows[i].Cells[3].Text = dt_status.Rows[j]["Fld"].ToString();

                }
                sql = "";
                sql = BC.GetBindSql("f515b80731a82d6b");
               
                DataTable dt_type = HDD.GetDataTable(sql);

                for (int j = 0; j < dt_type.Rows.Count; j++)
                {
                    if (GridAlert.Rows[i].Cells[3].Text == dt_type.Rows[j]["Val"].ToString())
                        GridAlert.Rows[i].Cells[3].Text = dt_type.Rows[j]["Fld"].ToString();

                }
                GridAlert.Rows[i].Cells[4].Text = duein;
                

            }
            foreach (GridViewRow row in GridAlert.Rows)
            {
                //CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                HyperLink link = (HyperLink)row.Cells[2].Controls[0];
                string str = GridAlert.DataKeys[row.RowIndex].Values[1].ToString();
                link.Text = str;
                string strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='aa922f981c2500e0';"); // pageset_id='task_config'
                link.NavigateUrl = "TaskConfig.aspx?pgs_id=aa922f981c2500e0&PK=" + GridAlert.DataKeys[row.RowIndex].Values[0].ToString() + "&mn=" + strMenuRowId; // pgs_id='task_config'
                //link.

            }
            lblHeader.Text = GridAlert.Rows.Count.ToString() + " Reminder(s)";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :Update Grid in AlertPopup" + ex.Message);
            
        }
        finally
        {
            loc = null;
            ddi = null;
            HDD = null;
            BC = null;
            
            
        }

    }

    public void CheckforTask()
    {
        GenerateAlerts GA = new GenerateAlerts();
        GA.GenerateAlert();
        GA = null;

    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    private string Message(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    protected void GridAlert_RowCreated(object sender, GridViewRowEventArgs e)
    {

        e.Row.Cells[1].Visible = false;

    }
    protected void GridAlert_RowDeleting(object sender, GridViewRowEventArgs e)
    {

        // e.Row.Cells[1].Visible = false;

    }

    protected void bt_dismiss_Click(object sender, EventArgs e)
    {
        arrSqlCmd.Clear();
        GenerateAlerts GA = new GenerateAlerts();
        try
        {
            int row_index;
            foreach (GridViewRow row in GridAlert.Rows)
            {
                CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                if (cbox != null && cbox.Checked)
                {
                    string row_id = row.Cells[1].Text;
                    GA.DismissTask(row_id);

                }
            }

           
            GetDuedate();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :Dismiss Click" + ex.Message);
            
        }
        finally
        {
            GA = null;
        }


    }

    protected void bt_defer_Click(object sender, EventArgs e)
    {

        arrSqlCmd.Clear();
        int row_index;
        GenerateAlerts GA = new GenerateAlerts();
        try
        {
            if (ddl_deferred.SelectedIndex != 0)
            {
                foreach (GridViewRow row in GridAlert.Rows)
                {
                    CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                    if (cbox != null && cbox.Checked)
                    {
                        string row_id = row.Cells[1].Text;
                        GA.DeferTask(row_id, ddl_deferred.SelectedValue);


                    }
                }
            }
         
            ddl_deferred.SelectedIndex = 0;
            GetDuedate();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :Defer Click" + ex.Message);

        }
        finally
        {
            GA = null;
        }
    }

    protected void GridAlert_RowDataBound(object sender, GridViewRowEventArgs e)
    {


    }
    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string GetUserTime(string input, string strUTCoffset, bool isForStoring)
    //{
    //    string sValue = "";
    //    string timeZoneOffest = strUTCoffset;
    //    DynamicDisplayI ddi = new DynamicDisplayI();
    //    Localization loc = new Localization();
    //    string sDateTimeFormatString = loc.getDateFormat() + " hh:mm tt";
    //    DateTime dt = new DateTime();
    //    try
    //    {
    //        string sHours = "";
    //        string sMinutes = "";
    //        bool isSystem = false;
    //        // if (input == "") return input;
    //        if (timeZoneOffest != "")
    //        {
    //            if (isForStoring)
    //            {
    //                if (timeZoneOffest.StartsWith("-"))
    //                    timeZoneOffest = "+" + timeZoneOffest.Substring(1);
    //                else if (timeZoneOffest.StartsWith("+"))
    //                    timeZoneOffest = "-" + timeZoneOffest.Substring(1);
    //                else if (timeZoneOffest.Trim() != "0")
    //                    timeZoneOffest = "+" + timeZoneOffest;
    //            }
    //            if (timeZoneOffest.IndexOf('.') != -1)
    //            {
    //                sHours = timeZoneOffest.Substring(1, timeZoneOffest.IndexOf('.') - 1);
    //                sMinutes = timeZoneOffest.Substring(timeZoneOffest.IndexOf('.') + 1, timeZoneOffest.Length - timeZoneOffest.IndexOf('.') - 1);
    //            }
    //            else
    //                sHours = timeZoneOffest.Substring(1, timeZoneOffest.Length - 1);

    //            if (timeZoneOffest.StartsWith("-"))
    //            {
    //                sHours = "-" + sHours;
    //                if (sMinutes != "")
    //                    sMinutes = "-" + sMinutes;
    //            }
    //        }
    //        if (sHours == "") sHours = "0";
    //        if (isForStoring)
    //            dt = DateTime.Parse(input, loc.getUserCulture());
    //        else
    //            dt = DateTime.Parse(input); //DateTime.Parse(input);//sanal on Sept 04, 2008
    //        dt = dt.AddHours(Convert.ToDouble(sHours));
    //        if (sMinutes != "")
    //            dt = dt.AddMinutes(Convert.ToDouble(sMinutes));
    //        if (isForStoring)
    //            sValue = dt.ToUniversalTime().ToString();
    //        else
    //            sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString); //dt.ToString(sDateTimeFormatStrin
    //        //sValue = dt.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
    //        //else
    //        // sValue = isSystem == true ? dt.ToString(sDateTimeFormatString) : dt.ToLocalTime().ToString(sDateTimeFormatString);
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("getInvariantDateTime : Error : " + ex.Message);
    //        sValue = "";
    //    }
    //    return sValue;
    //}
    #endregion

    //Added by 'Imran Gani' on 07-Jan-2014, for complete button
    protected void bt_task_completed_Click(object sender, EventArgs e)
    {
        arrSqlCmd.Clear();
        GenerateAlerts GA = new GenerateAlerts();
        try
        {
            foreach (GridViewRow row in GridAlert.Rows)
            {
                CheckBox cbox = (CheckBox)row.Cells[0].Controls[0];
                if (cbox != null && cbox.Checked)
                {
                    string row_id = row.Cells[1].Text;
                    GA.CompleteTask(row_id);
                }
            }
            GetDuedate();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :bt_task_completed_Click Click" + ex.Message);
        }
        finally
        {
            GA = null;
        }
    }
}
